package cn.zcj.studytest.service;

import cn.zcj.studytest.ThrowData.Result;
import cn.zcj.studytest.domain.SignUp;
import cn.zcj.studytest.mapper.SignUpMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class SignUpService extends ServiceImpl<SignUpMapper, SignUp> {
    public Result sinUpInsert(SignUp signUp){
        Result result = new Result();
        // 判断用户名是否重复
        SignUp one = this.lambdaQuery().eq(SignUp::getUsername, signUp.getUsername()).last("limit 1").one();
        if (Objects.nonNull(one)) {
          return  result.fail("已有账户名！");
        }
        double price = signUp.getPrice();
        if(!Objects.isNull(price)){
            signUp.setPrice(0);
        }
        this.save(signUp);
        result.ok("创建成功！");

        return result;
    }

    public Result login(SignUp signUp){
        Result result = new Result();
        SignUp one = this.lambdaQuery()
                .eq(SignUp::getUsername, signUp.getUsername())
                .eq(SignUp::getPassword, signUp.getPassword())
                .one();
        if (Objects.isNull(one)) {
            return result.fail("账号或密码错误！");
        }
        result.ok("登录成功！");
        result.setData(one.getId());
        return result;
    }

    public Result getUserInfo(SignUp signUp) {
        Result result = new Result();
        List<SignUp> list;
        Long id = signUp.getId();
        if(Objects.isNull(id)){
           list = this.list();
            result.setData(list);
        }else{
            list = this.lambdaQuery().eq(SignUp::getId, id).list();
            result.setData(list);
        }
        result.setData(list);
        result.ok("获取成功！");
        result.setSuccess(true);
        return result;
    }

    public SignUp getUserInfoOne(SignUp signUp) {

        return null;
    }

    public Result recharge(SignUp signUp) {
        Result result = new Result();
        SignUp one = this.lambdaQuery()
                .eq(SignUp::getId, signUp.getId()).one();

        if (Objects.isNull(one)) {
            return result.fail("账号不存在！");
        }
        Boolean isTrue = this.lambdaUpdate()
                .eq(SignUp::getId, signUp.getId())
                .set(SignUp::getPrice, one.getPrice() + signUp.getPrice())
                .update();
        if (!isTrue) {
            return result.fail("充值失败！");
        }
        result.ok("充值成功！");
        return result;
    }


}
